package com.huitone.gddw.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.Menu;
import com.huitone.gddw.dao.entity.Role;
import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.dao.entity.UserRole;
import com.huitone.gddw.dao.entity.Users;
import com.huitone.gddw.model.support.Message;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.dto.system.UsersDTO;
import com.huitone.gddw.service.system.IMenuService;
import com.huitone.gddw.service.system.IRoleMenuService;
import com.huitone.gddw.service.system.IRoleService;
import com.huitone.gddw.service.system.IUserRoleService;
import com.huitone.gddw.service.system.IUsersService;
import com.huitone.gddw.utils.SysLoginUtil;

/**
 * 用户管理 控制器
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="users")
public class UsersController extends CommonController {

	private final static Logger LOGGER = Logger.getLogger(UsersController.class);
	
	@Autowired
	private IUsersService usersService;
	
	@Autowired
	private IUserRoleService userRoleService;
	
	@Autowired
	private IRoleMenuService roleMenuService;
	
	@Autowired
	private IMenuService menuService;
	
	@Autowired
	private IRoleService roleService;
	
	/**
	 * 查询
	 * @param page
	 * @param request
	 * @return QueryPage
	 */
	@ResponseBody
	@RequestMapping(value="query")
	public QueryPage<UsersDTO> query(QueryPage<Users> page, HttpServletRequest request) {
		super.logType = SmLog.LOGTYPE_SELECT;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]查询用户管理列表";
		QueryPage<UsersDTO> result = null;
		try {
			page.setParams(getParams(request));
			result = usersService.selectPage(page);
		} catch (Exception e) {
			LOGGER.error("查询用户管理信息出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return result;
	}
	
	/**
	 * 获取参数信息
	 * @param request
	 * @return Map<String, Object>
	 */
	private Map<String, Object> getParams(HttpServletRequest request) {
		String userName = request.getParameter("userName");
		String phoneNumber = request.getParameter("phoneNumber");
		String deptId = request.getParameter("deptId");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userName", userName);
		params.put("phoneNumber", phoneNumber);
		params.put("deptId", deptId);
		return params;
	}
	
	/**
	 * 获取所有用户信息
	 * @return List<Users>
	 */
	@ResponseBody
	@RequestMapping(value="getAll")
	public List<Users> getAll() {
		try {
			return usersService.getAll();
		} catch (Exception e) {
			LOGGER.error("获取所有用户信息过程中出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 修改页面数据准备
	 * @param userId 用户ID
	 * @return UsersDTO
	 */
	@ResponseBody
	@RequestMapping(value="toUpdate")
	public UsersDTO toUpdate(String userId) {
		try {
			UsersDTO entity = usersService.toUpdate(userId);
			return entity;
		} catch (Exception e) {
			LOGGER.error("跳转修改页面过程中出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 更改状态
	 * @param userId 用户ID
	 * @param status 更改后状态
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="changeStatus")
	public Message changeStatus(String userId, String status) {
		try {
			Users entity = usersService.getById(userId);
			entity.setStatus(status);
			usersService.changeStatus(entity);
			return new Message(true, "操作成功！");
		} catch (Exception e) {
			LOGGER.error("更改用户管理状态过程中出现异常：" + e.getMessage(), e);
			return new Message(false, "操作失败！");
		}
	}
	
	/**
	 * 保存
	 * @param entity Users
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="save")
	public Message save(Users entity, String deptId) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]添加用户信息";
		try {
			Users user = usersService.getById(entity.getUserId());
			if (user != null) {
				super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
				return new Message(false, "该工号已存在，请重新输入！");
			}
			usersService.save(entity, deptId);
			super.saveSmLog(super.logType, super.logContent, super.logResult);
			return new Message(true, "保存成功！");
		} catch (Exception e) {
			LOGGER.error("保存用户管理信息过程中出现异常：" + e.getMessage(), e);
			super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
			return new Message(false, "保存失败！");
		}
	}
	
	/**
	 * 更新
	 * @param usersDTO UsersDTO
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="update")
	public Message update(UsersDTO usersDTO) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]修改用户信息";
		boolean isSuccess = true;
		String msg;
		try {
			usersService.update(usersDTO);
			msg = "修改成功！";
		} catch (Exception e) {
			LOGGER.error("修改用户管理信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "修改失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 删除
	 * @param userId 用户ID
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="delete")
	public Message delete(String userId) {
		super.logType = SmLog.LOGTYPE_DELETE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]删除用户信息";
		boolean isSuccess = true;
		String msg;
		try {
			usersService.delete(userId);
			msg = "删除成功！";
		} catch (Exception e) {
			LOGGER.error("删除用户管理信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "删除失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 获取用户所有角色
	 * @param userId 用户ID
	 * @return List
	 */
	@ResponseBody
	@RequestMapping(value="getUserRoles")
	public List<UserRole> getUserRoles(String userId) {
		try {
			List<UserRole> list = userRoleService.getByUserId(userId);
			return list;
		} catch (Exception e) {
			LOGGER.error("获取用户所有角色信息过程中出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 授权用户角色
	 * @param userId 用户ID
	 * @param roleIds 多个角色ID
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="changeUserRoles")
	public Message changeUserRoles(String userId, String roleIds) {
		try {
			userRoleService.changeUserRoles(userId, roleIds);
			return new Message(true, "授权成功！");
		} catch (Exception e) {
			LOGGER.error("授权用户过程中出现异常：" + e.getMessage(), e);
			return new Message(false, "授权失败！");
		}
	}
	
	/**
	 * 判断访问页面的权限
	 * @param html-Name
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="authentication")
	public Message authentication(HttpServletRequest request,String html) {
		boolean isSuccess = false;
		String msg = "暂无权限访问此页面！";
		try {
			 // 获取 Session  
	        HttpSession session = request.getSession();
	        // 获取用户信息
	        Users curLoginUser = session.getAttribute("curLoginUser") == null ? null : (Users)session.getAttribute("curLoginUser");
	        List<String> ids = new ArrayList<String>();
				List<Role> list = roleService.getByUserId(curLoginUser.getUserId());
				Set<String> s = new HashSet<String>();
				for (Role role : list) {
					List<String> l = roleMenuService.getMenuIdByRoleId(role.getRoleId());
					s.addAll(l);
				}
				ids.addAll(s);
				List<Menu> li = menuService.getByIds(ids);
				
			for(Menu me:li){
				String menuUrl = me.getMenuUrl();
				if(menuUrl!=null&&!menuUrl.equals("")){
					System.out.println(menuUrl);
					if(html.equals(menuUrl.split("/")[1])){
						msg = "有权限访问此页面！";
						isSuccess=true;
			        }
				}
				
			}
			
		} catch (Exception e) {
			LOGGER.error("判断页面权限过程中出现异常：" + e.getMessage(), e);
			isSuccess = false;
			msg = "暂无权限访问此页面！";
		}
		return new Message(isSuccess, msg);
	}
	
	
	/**
	 * 获取用户权限菜单
	 * @param userId 用户ID
	 * @return List<String>
	 */
	@ResponseBody
	@RequestMapping(value="getUserMenus")
	public List<Menu> getUserMenus(String userId) {
		List<String> ids = new ArrayList<String>();
		try {
			List<Role> list = roleService.getByUserId(userId);
			Set<String> s = new HashSet<String>();
			for (Role role : list) {
				List<String> l = roleMenuService.getMenuIdByRoleId(role.getRoleId());
				s.addAll(l);
			}
			ids.addAll(s);
			List<Menu> li = menuService.getByIds(ids);
			return li;
		} catch (Exception e) {
			LOGGER.error("授权用户过程中出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 退出系统
	 * @param request
	 * @param session
	 */
	/*@ResponseBody
	@RequestMapping(value="/logout")
	public Map<String, Object> logout(HttpServletRequest request, String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			String session = stringRedisTemplate.opsForValue().get(userId);
			if (session != null) {
				Users user = usersService.getById(userId);
				user.setOnlineStatus(Users.ONLINE_STATUS_OFF);
				usersService.update(user);
				
//				session.invalidate();
			}
			map.put("isSuccess", true);
			map.put("msg", "退出成功！");
			return map;
		} catch (Exception e) {
			LOGGER.error("退出出现异常：" + e.getMessage(), e);
			map.put("isSuccess", false);
			map.put("msg", "退出异常！");
			return map;
		}
	}*/
	
}
